import React from 'react';
import { Breadcrumb, Form, Input, Button, Select, InputNumber, Switch, Upload, Modal } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link } from 'react-router-dom';
import http from '../../http';
import BraftEditor from 'braft-editor'
import 'braft-editor/dist/index.css'
const layout = {
    labelCol: {
        span: 7,
    },
    wrapperCol: {
        span: 10,
    },
};
const tailLayout = {
    wrapperCol: {
        offset: 8,
        span: 16,
    },
};
const { Option } = Select;
function getBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
class AddShop extends React.Component {
    constructor(props) {
        super(props);
        this.state = { 
            firstGeneralList: [],
            secondGeneralList: [],
            previewVisible: false,//点击图片显示弹框
            previewImage: '',//弹框里的预览图片
            fileList: [], //图片列表
            editorState: BraftEditor.createEditorState(null), // 设置富文本初始内容
            outputHTML: '', // 富文本输出内容
            req: false,
            //提交所需参数
            name: '',
            subtitle: '',
            price: '',
            stock: '',
            status: '',
            detail: '',
            levelOneCategoryId: '',
            subImages: '',
            levelTwoCategoryId: '',
            categoryId: '',
            id: '',
            secondShow: false //显示二级分类
        }
    }
    firstGeneral = () => { //商品一级分类
        http.get('/api/manage/category/get_category.do?categoryId=0').then(res => {
            this.setState({
                firstGeneralList: res.data
            })
        })
    }
    valueChange = (value,values) => { //数据修改回调
        this.setState({
            name: values.name,
            subtitle: values.subtitle,
            price: values.price,
            stock: values.stock,
            status: values.status ? 1 : 2,
            levelOneCategoryId: values.firstGender,
            levelTwoCategoryId: values.secondGender
        })
        if (values.firstGender!==''&&this.state.req===false) {
            http.get('/api/manage/category/get_category.do?categoryId='+values.firstGender).then(res => {
                this.state.secondShow = true
                this.setState({
                    secondGeneralList: res.data,
                    req: true
                })
            })
        }
    }
    // 点击遮罩层或右上角叉或取消按钮的回调
    handleCancel = () => this.setState({ previewVisible: false });
    handlePreview = async file => { //点击文件链接或预览图标时的回调
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
        });
    };
    handleChange = ({ fileList }) => { // 上传文件改变时的状态
        // http.post('/api/manage/product/upload.do',{upload_file: (binary)}).then(res => {
        //     this.setState({ fileList })
        // })
        this.setState({ fileList })
        console.log(fileList)
    };
    addSubmit = () => { //提交
        const {name,subtitle,price,stock,status,detail,levelOneCategoryId,subImages,levelTwoCategoryId,categoryId,id} = this.state
// <p>好吃</p>
// 925b6edd-1e97-4f13-b5ef-825bad445ef8.jpg
        http.post('/api/manage/product/save.do',{name,subtitle,price,stock,status,detail,levelOneCategoryId,subImages,levelTwoCategoryId,categoryId:levelTwoCategoryId,id}).then(res => {
            this.props.history.push('/main/shop')
        })
    }
    componentDidMount() {
        this.firstGeneral()
    }
    render() { 
        const { previewVisible, previewImage, fileList, firstGeneralList, secondGeneralList, editorState, secondShow } = this.state;
        const firstOptions = firstGeneralList.map((item) =>
            <Option value={item.id} key={item.id}>{item.name}</Option>
        );
        const secondOptions = secondGeneralList.map((item) =>
            <Option value={item.id} key={item.id}>{item.name}</Option>
        );
        const uploadButton = (
            <div>
                <PlusOutlined />
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        const controls = [ //富文本需要展示的控件
            'undo', 'redo', 'separator',
            'font-size', 'line-height', 'letter-spacing', 'separator',
            'text-color', 'bold', 'italic', 'underline', 'strike-through', 'separator',
            'superscript', 'subscript', 'remove-styles', 'emoji', 'separator', 'text-indent', 'text-align', 'separator',
            'headings', 'list-ul', 'list-ol', 'blockquote', 'code', 'separator',
            'link', 'separator', 'hr', 'separator',
            'media',
            'separator',
            'clear'
        ]
        return ( 
            <div>
                <div className='breadcrumb-con'>
                    <Breadcrumb>
                        <Breadcrumb.Item>
                            <Link to='/main/home'>首页</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>商品</Breadcrumb.Item>
                        <Breadcrumb.Item>
                            <Link to='/main/shop'>商品列表</Link>
                        </Breadcrumb.Item>
                        <Breadcrumb.Item>新增商品</Breadcrumb.Item>
                    </Breadcrumb>
                    <h2>新增商品</h2>
                </div>
                <div className='shop-con'>
                <Form
                        {...layout}
                        initialValues={{
                            remember: true,
                        }}
                        // onFinish={this.onFinish}
                        // initialValues={this.state.detail}
                        onValuesChange={this.valueChange}
                    >
                        <Form.Item
                            label="商品名称"
                            name="name"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="商品描述"
                            name="subtitle"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            name="firstGender"
                            label="商品一级分类"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Select>
                                {firstOptions}
                            </Select>
                        </Form.Item>
                        {secondShow ? <Form.Item
                            name="secondGender"
                            label="商品二级分类"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Select>
                                {secondOptions}
                            </Select>
                        </Form.Item> : ''}
                        <Form.Item
                            label="价格"
                            name="price"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <InputNumber />
                        </Form.Item>
                        <Form.Item
                            label="库存"
                            name="stock"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <InputNumber />
                        </Form.Item>
                        <Form.Item
                            label="上架状态"
                            name="status"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Switch checkedChildren="上架" unCheckedChildren="下架" defaultChecked />
                        </Form.Item>
                        <Form.Item
                            label="图片上传"
                            name="images"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <Upload
                                action="http://localhost:3000/api/manage/product/upload.do"
                                listType="picture-card"
                                fileList={fileList}
                                onPreview={this.handlePreview}
                                onChange={this.handleChange}
                            >
                                {fileList.length >= 8 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                        </Form.Item>
                        <Form.Item
                            label="详情"
                            name="detail"
                            rules={[
                                {
                                    required: true,
                                    message: '此项为必填项!',
                                },
                            ]}
                        >
                            <div style={{border: '1px solid rgb(191, 191, 191)'}}>
                                <BraftEditor
                                    value={editorState}
                                    controls={controls}
                                    contentStyle={{height: 500, fontSize: '16px', paddingBottom: '10px'}}
                                    onChange={this.changeHtml}
                                />
                            </div>
                        </Form.Item>
                        <Form.Item {...tailLayout}>
                            <Button type="primary" htmlType="submit" onClick={this.addSubmit}>提交</Button>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        );
    }
}
 
export default AddShop;